
var table;//全局Table对象，方便后面直接引用分页
var mytooljs = {
		//初始化表格
	initTable:function(_initParam){
	var initParam = {
			idSelecter : "#table1",	//表格默认id
			sendurl:_initParam.sendurl||"", 
			searchForm:_initParam.searchForm||"#searchFrom",
			pagesize:_initParam.pagesize||10,
			afterload:_initParam.afterload||null ,//数据加载成功后调得函数
			delUrl:_initParam.delUrl||"",//删除数据的地址
			editUrl:_initParam.editUrl||"",//打开编辑页面地址
			title:_initParam.title||"新增和编辑页",//打开的页面标题
			windowSize:_initParam.windowSize||{'X':'80%','Y':'80%'}
			}

			table = new Table(initParam);
			table.init();
			return table;
	},
	initSelect:function(_initParam){//初始化下拉框
		var initParam = {
			idSelecter :_initParam.idSelecter||"#autoselect" //select默认id
			}
		var select = new Select(initParam);
		select.init();
		return select;
	},initForm:function(_initParam){//初始化表单
		var initParam = {
			idSelecter :_initParam.idSelecter||"#from1", //form默认id
			sendurl:_initParam.sendurl||"",
			afterload:_initParam.afterload||null //数据加载成功后调得函数
			}
		var form = new Form(initParam);
		form.init();
		return form;
	},
	redirect : function(url) {
		window.location.href = url;
	},
	/** 页面定向 无视iframe */
	toPredirect : function(url) {
		window.top.location.href = url;
	},
	getTime : function(value) {
		var temp = "";
		try {
			temp = value
			var date = new Date(temp);
			if (!temp) {
				return "";
			} else {
				return date.getFullYear() + "-" + setFomartZero((date.getMonth() + 1))
				+ "-" + setFomartZero(date.getDate()) + " " + setFomartZero(date.getHours())
				+ ":" + setFomartZero(date.getMinutes());
			}
		} catch (e) {
			console.err('getTime执行失败');
		}
		return temp;
	},getTimeDD : function(value) {
		var temp = "";
		try {
			temp = value
			var date = new Date(temp);
			if (!temp) {
				return "";
			} else {
				return date.getFullYear() + "-" + setFomartZero((date.getMonth() + 1))
				+ "-" + setFomartZero(date.getDate());
			}
		} catch (e) {
			console.err('getTime执行失败');
		}
		return temp;
	}
	
	
}
function setFomartZero(date){
	if(date<10){
		return "0"+date;
	}
	return date;
}
function Select(initParam){
	this.init=function(){
		getdata();
	}
	var getdata=function(){
		var _select =$(initParam.idSelecter);
		var _datas =_select.data();
		$.ajax({
	  		'type':'post',
	  		'url':_datas.url,
	  		'data':'',
	  		'dataType':'json',
	  		'success':function(data,status){
	  			var html = '';
	  			html+="<option value=''>所有</option>";
	  			for(var i=0;i<data.rows.length;i++){
	  				html+="<option value='"+data.rows[i][_datas.value]+"' ";
	  				if(data.rows[i][_datas.value]==_datas.def){
	  					html+="selected='selected'";
	  				}
	  				html+="  >"+data.rows[i][_datas.show]+"</option>";
	  			}
	  			_select.append(html);
	  		}
	  	}); 
	}
}


function Table(initParam){
	//初始化分页参数
	var sumpage;
	var data = {"offset":0,"limit":initParam.pagesize,"currpage":1};
	var el = $(initParam.idSelecter);
//	el.attr({"class":""});
	var id =initParam.idSelecter.substring(1,initParam.idSelecter.length);//去掉#的id用原生js拿表头
	var tableObj = document.getElementById(id);
	var arr = new Array();//房data-name属性得数组
	var arrfun = new Array();//放data-format属性得数组
	//遍历表头,获取每个单元得data-name和data-format属性
	for (var j = 0; j < tableObj.rows[0].cells.length; j++) {
	var cellobj = tableObj.rows[0].cells[j];
	arr[j] = cellobj.getAttribute("data-name");
	if(cellobj.getAttribute("data-format")!=undefined){
		arrfun[j]=cellobj.getAttribute("data-format");
	}else{
		arrfun[j]=datanoformat;//如果没传转换方法那就默认方法
	}

		}
	this.init=function(){
		getdata(data);
	}
	this.chagePage=function(currpage){
		if(currpage!=null&&currpage!=undefined){
			//如果传了页数，当前页数*页数量
			var data_ = {"currpage":currpage,"offset":(currpage-1)*initParam.pagesize,"limit":currpage*initParam.pagesize};
			console.log("传了页数");
			console.log(data_);
			data = $.extend(data, data_);
		}
		getdata(data);
	}
	//跳转
	this.skip=function(num){
		var currpage;
		if(num!=null){
			currpage=num;
		}else{
			currpage = $("#numbers").val();
		}
		if(currpage!=null&&currpage!=undefined&&currpage.length>0){
			//如果传了页数，当前页数*页数量
			if(currpage>sumpage)
			currpage=sumpage;
			var data_ = {"currpage":currpage,"offset":(currpage-1)*initParam.pagesize,"limit":currpage*initParam.pagesize};
			data = $.extend(data, data_);
			getdata(data);
		}
	}
	this.search=function(){
		var _data = serializeForm(initParam.searchForm);
		console.log(_data);
		console.log("表单json");
		//带了条件才重新定位到第一页
		if(_data!=null){
		data = {"offset":0,"limit":initParam.pagesize};//初始化当前页为第一页
		data = $.extend(data, _data);
		}
		console.log(data);
		//重新加载数据
		getdata(data);
	}
	this.refCurr=function(){
		var page = '';
		var thiscpagefont = document.getElementById("cpagefont");
		var	parentcpagefont = window.parent.document.getElementById("cpagefont");
		if( thiscpagefont == null&&parentcpagefont==null){
			//还没达到分页的数量
			table.search();
			return ;
		}else if (thiscpagefont!=null){
			page = thiscpagefont.innerHTML;
		}else{
			page = parentcpagefont.innerHTML;
		}
		page = 	parseInt(page.replace(/[^0-9]/ig,""));
		//定位到当前页
		var data = {"currpage":page,"offset":(page-1)*initParam.pagesize,"limit":page*initParam.pagesize};
		//重新加载数据
		getdata(data);
	}
	this.delRec=function(id){	//删除方法
			var durl = initParam.delUrl+"?id="+id;
			console.log(durl);
			$.ajax({
		  		'type':'post',
		  		'url':durl,
		  		'data':'',
		  		'dataType':'json',
		  		'success':function(data,status){
		  			layer.alert(data.info);
		  			table.search();//重新加载数据
		  		}
		  	}); 
}
	this.editFrom=function(id){//打开编辑页面
		var eurl=initParam.editUrl;
		//传了id带id编辑没新增
		if(id!=undefined){
			eurl+="?id="+id;
		}
		layer.open({
			type : 2,
			title : initParam.title,
			area : [ initParam.windowSize.X,initParam.windowSize.Y ],
			maxmin : true,
			content : [eurl]
		});
			
}
	
	function datanoformat(value,index){
		value+="";
		if(value.indexOf("script")!=-1){
			value="非法输入";
		}else if(value==null||value=="null"){
			value="";
		}
		 return value;
	}
	
	var getdata=function(data){
			console.log("getdata");
			console.log(data);
			var tb =initParam.idSelecter+" tbody";
			$(tb).remove();
			$("#tablediv input").remove();
			$("#tablediv span").remove();
			var html="";
					$.ajax({
				  		'type':'post',
				  		'url':initParam.sendurl,
				  		'data':data,
				  		'dataType':'json',
				  		'success':function(data,status){
				  			html+="<tbody>";
				  			for(var obj=0;obj<data.rows.length;obj++){
				  				html+="<tr>";
				  				for(var i=0;i<arr.length;i++){
				  					if(obj%2==0){
				  						html+="<td>";	
				  					}else{
				  						html+="<td>";	
				  					}
				  					if(initParam.afterload!=null){
				  						var fun=eval(initParam.afterload);//eval执行方法名称得到方法体
					  					fun();
				  					}
				  					
				  					var format = eval(arrfun[i]);
				  					//console.log(format);
				  					var value = format(data.rows[obj][arr[i]],obj);//传值进行数格式得转换
				  					html+=value;
				  					html+="</td>";
				  					
				  					
				  				}
				  				html+="</tr>";
				  			}
				  			//上一页，下一页。调用search方法。传入页数，
				  			var last = Number(data.page)-1;
				  			var last1 = "<input type='button' style='display:inline-block;margin:5px;' value='上一页' class='btn btn-default btn-sm' onclick='table.chagePage("+last+")'/>";
				  			var next = Number(data.page)+1;
				  			var next1="<input type='button'  style='display:inline-block;margin:5px;' value='下一页' class='btn btn-default btn-sm' onclick='table.chagePage("+next+")'/>";
				  			if(last<=0){//当前页-1小于等于0 取消掉上一页按钮
				  				last1="<input type='button' style='display:inline-block;margin:5px;' value='上一页' class='btn btn-default btn-sm' disabled='disabled' onclick='table.chagePage("+last+")'/>";
				  			}else if(data.page*initParam.pagesize>=data.total){//当前页*每页记录大于等于总记录 //取消下一页按钮
				  				next1="<input type='button' style='display:inline-block;margin:5px;' value='下一页' class='btn btn-default btn-sm' disabled='disabled' onclick='table.chagePage("+next+")' />";
				  			}
				  			//如果返回数据总数大于单页记录数，显示上下页按钮
				  			
				  			html+="</tbody>";
				  			el.append(html);
				  			var btn='';
				  			if(data.total>initParam.pagesize){
				  				btn+="<div class='text-center'>";
				  				btn+="<input type='number' id='numbers'   style='display:inline-block;margin:5px;'/>";
				  				btn+="<input type='button' value='GO' onclick='table.skip()' class='btn btn-default btn-sm' style='display:inline-block;margin:5px;'/>";
					  			console.log(data.info);
					  			btn+=last1;
					  			btn+=next1;
					  			sumpage=Math.ceil((data.total/initParam.pagesize));
					  			var tx="<span class='text-right' id='cpagefont'>第"+data.page+"页</span><span class='text-right'>/共"+sumpage+"页</span>";
					  			btn+=tx;
					  			btn+="</div>";
				  			}
				  			$("#tablediv").append(btn);
				  			//所有数据加载成功后回调
				  			if(initParam.afterload!=null){
								var fun=eval(initParam.afterload);//eval执行方法得到方法体
								fun();
							}
				  		}
				  	}); 
	}
	}

//表单对象
function Form(initParam){
	var data = serializeForm(initParam.idSelecter);//表单id
	console.log(data);
	this.init=function(){
			$.ajax({
		  		'type':'post',
		  		'url':initParam.sendurl,
		  		'data':data,
		  		'dataType':'json',
		  		'success':function(data,status){
		  			layer.msg(data.info);
		  			if(initParam.afterload!=null){
					var fun=eval(initParam.afterload);//eval执行方法得到方法体
					fun();
					}
		  		}
		  	});
	}
}

//序列表单成json
function serializeForm(formId) {  
	var json="";
	var fields = $(formId).serializeArray();
	console.log(fields);
	$.each(fields,function(i, field){
	  	json+="'"+field.name+"':'"+field.value+"',";
	});
	json="{"+json.substr(0,json.length-1)+"}";
	console.log(json);
	json = eval("("+json+")");
	console.log(json);
	return json;
}
